<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { nextTick } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { eachTree } from '@vben/utils';

import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deviceProperty } from '#/api/iot/device/manage';

import { columns, querySchema } from './data';

const [BasicDrawer, drawerApi] = useVbenDrawer({
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    tableApi.reload();
  },
  onClosed() {
    tableApi.setGridOptions({
      data: [],
    });
  },
});

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  showCollapseButton: false,
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3',
};

const timeHandle = (minute: number, rangeTime: string[]) => {
  let queryStartTime: string = '';
  let queryEndTime: string = '';

  if (minute === 0) {
    if (rangeTime && rangeTime.length === 2) {
      queryStartTime = rangeTime[0] ?? '';
      queryEndTime = rangeTime[1] ?? '';
    }
  } else {
    if (minute) {
      queryEndTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
      queryStartTime = dayjs(new Date())
        .subtract(minute, 'minute')
        .format('YYYY-MM-DD HH:mm:ss');
    }
  }
  return [queryStartTime, queryEndTime];
};

const gridOptions: VxeGridProps = {
  columns,
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const { itemId, deviceId } = drawerApi.getData();
        const [queryStartTime, queryEndTime] = timeHandle(
          formValues.timeInterval,
          formValues.timeIntervalRange,
        );
        const resp = await deviceProperty({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
          queryStartTime,
          queryEndTime,
          deviceId,
          itemId,
        });
        return resp;
      },
      // 默认请求接口后展开全部 不需要可以删除这段
      querySuccess: () => {
        // 默认展开 需要加上标记

        eachTree(tableApi.grid.getData(), (item) => (item.expand = true));
        nextTick(() => {
          setExpandOrCollapse(true);
        });
      },
    },
  },
  /**
   * 虚拟滚动  默认关闭
   */
  scrollY: {
    enabled: false,
    gt: 0,
  },
  rowConfig: {
    keyField: 'deptId',
  },
  treeConfig: {
    parentField: 'parentId',
    rowField: 'deptId',
    transform: true,
  },
  id: 'history-data-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    cellDblclick: (e) => {
      const { row = {} } = e;
      if (!row?.children) {
        return;
      }
      const isExpanded = row?.expand;
      tableApi.grid.setTreeExpand(row, !isExpanded);
      row.expand = !isExpanded;
    },
    // 需要监听使用箭头展开的情况 否则展开/折叠的数据不一致
    toggleTreeExpand: (e) => {
      const { row = {}, expanded } = e;
      row.expand = expanded;
    },
  },
});

/**
 * 全部展开/折叠
 * @param expand 是否展开
 */
function setExpandOrCollapse(expand: boolean) {
  eachTree(tableApi.grid.getData(), (item) => (item.expand = expand));
  tableApi.grid?.setAllTreeExpand(expand);
}
</script>

<template>
  <BasicDrawer title="历史数据" class="w-[1000px]" :footer="false">
    <BasicTable table-title="历史数据">
      <template #customervalue="{ row }">
        {{
          (() => {
            const key = Object.keys(row).find((key) => key !== 'ts');
            return key ? row[key] : '';
          })()
        }}
      </template>
    </BasicTable>
  </BasicDrawer>
</template>
